import jwt from "jsonwebtoken";
import { ObjectId } from "mongodb";

const JWT_SECRET = process.env.JWT_SECRET || "your-jwt-secret-key";

const authMiddleware = (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    const token = authHeader?.replace("Bearer ", "");

    if (!token) {
      return res.status(401).json({ error: "未提供认证令牌" });
    }

    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = {
      userId: new ObjectId(decoded.userId),
      username: decoded.username,
      role: decoded.role || "user",
    };

    next();
  } catch (error) {
    console.error("认证中间件错误:", error);
    res.status(401).json({ error: "无效的认证令牌" });
  }
};

// 关键：使用默认导出
export default authMiddleware;
